package com.cloud.sample.controller;

import com.cloud.common.bean.ResultInfo;
import com.cloud.sample.provider.MinioProvider;
import com.cloud.sample.provider.QcloudCosProvider;
import com.cloud.sample.provider.dto.QcloudCosCredentialDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;

@Slf4j
@RestController
public class FileController {
    @Autowired
    private MinioProvider minioProvider;

    @Autowired
    private QcloudCosProvider qcloudCosProvider;

    /**
     * 获取临时凭证
     *
     * @return ResultInfo
     * @throws Exception
     */
    @PostMapping(value = "/file/getCredential")
    public ResultInfo<QcloudCosCredentialDTO> getCredential() throws Exception {
        return ResultInfo.success().setData(qcloudCosProvider.getCredential());
    }

    /**
     * 上传文件
     *
     * @param file
     * @return ResultInfo
     * @throws Exception
     */
    @PostMapping(value = "/file/upload")
    public ResultInfo<String> upload(boolean noCompress, @RequestParam("file") MultipartFile file) throws Exception {
        String fileName = minioProvider.uploadFile(file, noCompress);
        return ResultInfo.success().setData(minioProvider.getFileUrl(fileName));
    }

    /**
     * 下载文件
     *
     * @param fileName
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/file/download")
    public void download(String fileName, HttpServletResponse response) throws Exception {
        String attachmentFilename = "attachment;filename=" + URLEncoder.encode(fileName, CharEncoding.UTF_8);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, attachmentFilename);
        response.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE);
        InputStream in = minioProvider.downloadFile(fileName);
        IOUtils.copy(in, response.getOutputStream());
        in.close();
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return ResultInfo
     * @throws Exception
     */
    @GetMapping(value = "/file/delete")
    public ResultInfo<String> delete(String fileName) throws Exception {
        minioProvider.deleteFile(fileName);
        return ResultInfo.success();
    }
}
